package com.ylxn.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.ylxn.io.Resources;
import com.ylxn.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用dom4j将配置文件进行解析封装成Configuration
     *
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws Exception {

        Document document = new SAXReader().read(inputStream);
        //获取根对象
        Element rootElement = document.getRootElement();
        //获取标签为propertiy标签元素
        List<Element> list = rootElement.selectNodes("//propertiy");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }
        //创建数据连接池
        ComboPooledDataSource pooledDataSource = new ComboPooledDataSource();
        pooledDataSource.setPassword(properties.getProperty("password"));
        pooledDataSource.setUser(properties.getProperty("username"));
        pooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        pooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        configuration.setDataSource(pooledDataSource);

        //mapper.xml解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }
        return configuration;
    }
}
